package ca.etsmtl.log430.lab3;

import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 
 */

public class SortByStateFilter extends Thread {

	// Declarations

	boolean done;

	PipedReader inputPipe = new PipedReader();
	PipedWriter outputPipe = new PipedWriter();

	public SortByStateFilter(PipedWriter inputPipe,
			PipedWriter outputPipe) {

		try {

			// Connect inputPipe
			this.inputPipe.connect(inputPipe);
			System.out.println("SortByState :: connected to upstream filter.");

			// Connect outputPipe
			this.outputPipe = outputPipe;
			System.out.println("SortByState :: connected to downstream filter.");

		} catch (Exception Error) {
			System.out.println("SortByState :: error connecting to other filters.");

		} // try/catch

	} // Constructor

	// This is the method that is called when the thread is started
	public void run() {

		// Declarations

		char[] characterValue = new char[1];
		// char array is required to turn char into a string
		String lineOfText = "";
		// string is required to look for the keyword
		int integerCharacter; // the integer value read from the pipe
		
		List<Project> projects = new ArrayList<Project>();

		try {

			done = false;

			while (!done) {

				integerCharacter = inputPipe.read();
				characterValue[0] = (char) integerCharacter;

				if (integerCharacter == -1) { // pipe is closed

					done = true;

				} else {

					if (integerCharacter == '\n') { // end of line

						System.out.println("SortByState :: received: " + lineOfText + ".");
						projects.add(new Project(lineOfText));
						lineOfText = "";

					} else {

						lineOfText += new String(characterValue);

					} // if //

				} // if

				if(done){
					Collections.sort(projects);
					
					for(Project p : projects){
						String output = "";
						output = p.lineOfText;
						System.out.println("SortByState :: sending: "
								+ output + " to output pipe.");
						outputPipe.write(output, 0, output.length());
						outputPipe.write((int) '\n');
						outputPipe.flush();
					}
				}

			} // while

		} catch (Exception error) {

			System.out.println("SortByState:: Interrupted.");
			error.printStackTrace();

		} // try/catch

		try {

			inputPipe.close();
			System.out.println("SortByState " + ""
					+ ":: input pipe closed.");

			outputPipe.close();
			System.out.println("SortByState " + ""
					+ ":: output pipe closed.");

		} catch (Exception error) {

			System.out.println("SortByState " + ""
					+ ":: Error closing pipes.");

		} // try/catch

	} // run

} // class